package com.dmzapp.api.db;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.vo.AppBid;
import com.dmzapp.api.vo.AppInfo;
import com.dmzapp.api.vo.IbatisSearchRequest;
import com.dmzapp.api.vo.IncomeRecord;
import com.dmzapp.api.vo.IncomeType;
import com.dmzapp.api.vo.LongUseRecord;
import com.dmzapp.api.vo.OutRecord;
import com.dmzapp.api.vo.UserAccount;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class AppDao {

    private SqlMapClient smc = null;
    private static AppDao appDao = new AppDao();
    Logger logger = LoggerFactory.getLogger("dmzlog");
    
    private AppDao() {
        init();
    }

    private void init() {
        if (smc == null) {
            Reader rd;
            try {
                rd = Resources.getResourceAsReader("SqlMapConfig.xml");
                smc = SqlMapClientBuilder.buildSqlMapClient(rd);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static AppDao getInstance() {

        return appDao;

    }

    public boolean insertUseroutrecord(OutRecord record) {
        try {
            smc.insert("total.insertOutcomeHistory", record);
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);

        }
        return false;
    }
    
    public List<OutRecord> getOutcomelistByusername(String username) {
        List<OutRecord> result = null;
        
        try {
            result = (List<OutRecord>) smc.queryForList("total.getUserOutcomeList", username);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return result;
    }
    
    public List<IncomeRecord> getIncomelistByusername(String username) {
        List<IncomeRecord> result = null;
        
        try {
            result = (List<IncomeRecord>) smc.queryForList("total.getUserIncomeList", username);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return result;
    }
    
    public boolean updateSinainfo4Enduser(UserAccount useraccount) {
        boolean flg = false;
        
        try {
            int i = smc.update("total.updateSinainfo4Enduser", useraccount);
            if (i == 1) {
                flg = true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return flg;
    }
    
    public boolean updateQQinfo4Enduser(UserAccount useraccount) {
        boolean flg = false;
        
        try {
            int i = smc.update("total.updateQQinfo4Enduser", useraccount);
            if (i == 1) {
                flg = true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return flg;
    }
    
    public boolean insertEnduser(UserAccount useraccount) {
        boolean flg = false;
        
        try {
            smc.insert("total.insertEnduser", useraccount);
            
            flg = true;
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return flg;
    }
    
    public UserAccount getMacDevice(String mac, String deviceid) {

        UserAccount in = new UserAccount();
        in.setMac_address(mac);
        in.setDeviceid(deviceid);

        UserAccount result = null;

        List<UserAccount> list = null;
        try {
            list = (List<UserAccount>) smc.queryForList("total.getMacDevice", in);

            if (list != null && list.size() == 1) {
                result = list.get(0);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        
        return result;
    }

    public UserAccount getMacDeviceidByqq(String qq) {
        UserAccount result = null;

        List<UserAccount> list = null;
        try {
            list = (List<UserAccount>) smc.queryForList("total.getMacDeviceidByqq", qq);

            if (list != null && list.size() == 1) {
                result = list.get(0);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }

        return result;
    }

    public UserAccount getMacDeviceidBysina(String sina) {
        UserAccount result = null;

        List<UserAccount> list = null;
        try {
            list = (List<UserAccount>) smc.queryForList("total.getMacDeviceidBysina", sina);

            if (list != null && list.size() == 1) {
                result = list.get(0);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }

        return result;
    }

    public List<LongUseRecord> getLongtimeuseListbyUsernameGroupbypackage(String username, int serviceid) {
        List<LongUseRecord> list = null;
        try {
            IbatisSearchRequest request = new IbatisSearchRequest();
            request.setUsername(username);
            request.setServiceid(serviceid);
            list = (List<LongUseRecord>) smc.queryForList("total.getLongtimeuseListbyUsernameGroupbypackage", request);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }

        return list;
    }

    public List<String> getInstallPackalistByusername(String username) {
        List<String> list = null;
        try {
            list = (List<String>) smc.queryForList("total.getInstallPackageListbyUsername", username);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }

        return list;
    }

    public UserAccount getUserInfo(String username) {

        UserAccount userinfo = null;
        try {
            List<UserAccount> temp = (List<UserAccount>) smc.queryForList("total.getUserInfoByusername", username);

            if (temp != null && temp.size() == 1) {
                userinfo = temp.get(0);
                userinfo.setUsername(username);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }

        return userinfo;

    }

    /**
     * 高并发写：扩展方向采用consistant hash进行分库写
     * 
     * @param incomeHistory
     * @return
     */
    public boolean insertIncomeHistory(IncomeRecord incomeHistory) {

        try {
            smc.insert("total.insertIncomeHistory", incomeHistory);
            return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);

        }

        return false;

    }

    public double getRestMoneyBypackage(String packagename) {
        List<AppInfo> list = null;
        try {
            list = (List<AppInfo>) smc.queryForList("total.getRestMoneyBypackage", packagename);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        double result = 0;
        if (list != null && list.size() == 1) {
            result = list.get(0).getRest_total();
        }
        return result;
    }

    public List<AppInfo> getAllActiveApps() {
        List<AppInfo> list = null;
        List<AppBid> middleList = null;
        try {
            list = (List<AppInfo>) smc.queryForList("total.getAllApps");
            middleList = (List<AppBid>) smc.queryForList("total.getAlappbids");
            Map<Integer, Map<Integer, Double>> tmpMap = new HashMap<Integer, Map<Integer, Double>>(middleList.size());
            for (AppBid bid : middleList) {
                if (tmpMap.get(bid.getAppid()) == null) {
                    tmpMap.put(bid.getAppid(), new HashMap<Integer, Double>());
                }

                // 特殊处理，当serviceid大于4时，用的别的体验套餐，取巧直接用2作为key供下面for循环logtimeuserfee赋值 
                tmpMap.get(bid.getAppid()).put(bid.getServiceid() > 4 ? 2 : bid.getServiceid(), bid.getUnit_bid());

            }

            for (AppInfo app : list) {
                //TODO: 
                app.setDownloadFee(tmpMap.get(app.getId()).get(IncomeType.DOWLOAD) == null ? 0 : tmpMap
                        .get(app.getId()).get(IncomeType.DOWLOAD));
                app.setLongtimeuserFee(tmpMap.get(app.getId()).get(IncomeType.LONG_TIME_USER) == null ? 0 : tmpMap.get(
                        app.getId()).get(IncomeType.LONG_TIME_USER));
                app.setRateFee(tmpMap.get(app.getId()).get(IncomeType.RATE) == null ? 0 : tmpMap.get(app.getId()).get(
                        IncomeType.RATE));
                app.setForwardFee(tmpMap.get(app.getId()).get(IncomeType.FORWARD_WEIBO) == null ? 0 : tmpMap.get(
                        app.getId()).get(IncomeType.FORWARD_WEIBO));
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        return list;
    }
    
    public static void main(String[] args) {
//        AppDao.getInstance().init();
//        
//        List<LongUseRecord> i = AppDao.getInstance().getLongtimeuseListbyUsernameGroupbypackage("pwq1985-1208@163.com", 1);
//    
//        System.out.println(i.get(0).getUseTimes());
        
//        int i = 6;
//
//        int j = 12;
//
//        i = (j - i) + (j = i);
//        
//        System.out.println(i);
//        System.out.println(j);
        
//        System.out.println(timeToCn(Calendar.getInstance().getTimeInMillis() + 40 * 1000));
//        Date date = AppDao.getInstance().getOutcomelistByusername("1934667433").get(0).getCreate_time();
//        
//        System.out.println(date);
//        
//        System.out.println(new Date(date.getTime()));
        
        AppDao.getInstance().getAllActiveApps();
    }
    
    public static String timeToCn(long dateLongValue) {
        
        Date date = new Date(dateLongValue);
        if (date == null) {
            return "";
        }
        long cha = (date.getTime() - new Date().getTime()) / 1000;
        long day = cha / (24 * 3600);
        long hour = cha % (24 * 3600) / 3600;
        long minute = cha % 3600 / 60;
        String str = "";
        if (day >= 1) {
            str = day + "天后";
        } else if (day < 1 && hour >= 1) {
            str = hour + "小时后";
        } else if (hour < 1 && minute > 1) {
            str = minute + "分钟后";
        } else {
            str = "数秒后";
        }
        return str;
    }
}
